package cn.seifly.demo.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.sql.SqlUtil;

import java.util.List;

/**
 * MyBatis-Plus 分页工具类
 * 
 * @author seifly
 */
public class MyBatisPlusPageUtils {
    
    /**
     * 创建分页对象
     */
    public static <T> Page<T> getPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        
        Page<T> page = new Page<>(pageNum, pageSize);
        
        // 处理排序
        if (orderBy != null && !orderBy.isEmpty()) {
            // MyBatis-Plus 的排序格式需要转换
            String[] orderItems = orderBy.split(",");
            for (String item : orderItems) {
                if (item.trim().isEmpty()) continue;
                
                String[] parts = item.trim().split(" ");
                String column = parts[0];
                boolean isAsc = parts.length > 1 && "asc".equalsIgnoreCase(parts[1]);
                
                if (isAsc) {
                    page.addOrder((List<OrderItem>) Wrappers.<T>query().orderByAsc(column));
                } else {
                    page.addOrder((List<OrderItem>) Wrappers.<T>query().orderByDesc(column));
                }
            }
        }
        
        return page;
    }
    
    /**
     * 创建分页对象（不排序）
     */
    public static <T> Page<T> getPageWithoutOrder() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        
        return new Page<>(pageNum, pageSize);
    }
    
    /**
     * 转换为若依的分页返回格式
     */
    public static <T> com.ruoyi.common.core.page.TableDataInfo convertToTableDataInfo(IPage<T> page) {
        com.ruoyi.common.core.page.TableDataInfo rspData = new com.ruoyi.common.core.page.TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(page.getRecords());
        rspData.setTotal(page.getTotal());
        return rspData;
    }
}